package com.manong.bookstore.user.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manong.common.utils.PageUtils;
import com.manong.common.utils.Query;

import com.manong.bookstore.user.dao.AddressDao;
import com.manong.bookstore.user.entity.AddressEntity;
import com.manong.bookstore.user.service.AddressService;
import org.springframework.transaction.annotation.Transactional;


@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressDao, AddressEntity> implements AddressService {

//    @Override
//    public PageUtils queryPage(Map<String, Object> params) {
//        IPage<AddressEntity> page = this.page(
//                new Query<AddressEntity>().getPage(params),
//                new QueryWrapper<AddressEntity>()
//        );
//
//        return new PageUtils(page);
//    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //1、获取key
        String key = (String) params.get("key");
        QueryWrapper<AddressEntity> queryWrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(key)){
            queryWrapper.eq("address_id",key)
                    .or().eq("user_id",key)
                    .or().eq("gender",key)
                    .or().like("first_name",key)
                    .or().like("last_name",key)
                    .or().like("phone_number",key)
                    .or().like("area",key)
                    .or().like("detail_address",key);
        }

        IPage<AddressEntity> page = this.page(
                new Query<AddressEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public boolean setDefaultAddress(String userId, String addressId) {
        if(userId == null || addressId == null)
            return false;

        List<AddressEntity> result = baseMapper.selectList(new QueryWrapper<AddressEntity>().eq("user_id", userId).eq("is_default", "1"));

        for(AddressEntity addressEntity : result) {
            addressEntity.setIsDefault(0);
            baseMapper.updateById(addressEntity);
        }

        AddressEntity newAddress = baseMapper.selectById(addressId);

        System.out.println("addressService.setDefault: newId: " + newAddress.getAddressId());

        newAddress.setIsDefault(1);
        baseMapper.updateById(newAddress);

        return true;
    }

}